package com.lyj.ui.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.lyj.pojo.Option;
import com.lyj.pojo.Subject;
import com.lyj.pojo.User;
import com.lyj.service.SubjectService;
import com.lyj.service.impl.SubjectServiceImpl;
import com.lyj.util.RuleException;
import com.lyj.util.format.DateUtil;

@WebServlet({"/DoAddServlet","/m/doAdd"})
public class DoAddServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//获取浏览器提交的数据
		String sid = request.getParameter("id");
		String title= request.getParameter("title");
		String number = request.getParameter("number");
		//页面上可以多个表单元素同name，
		String[] options = request.getParameterValues("options");		
        String startTime = request.getParameter("startTime");
        String endTime = request.getParameter("endTime");
		
		//实体类对象作为数据载体
		Subject subject = new Subject();
		subject.setTitle(title);
		if(number == null) {
			number = "0";
		}
		subject.setNumber(Integer.parseInt(number));
		for(String content:options){
			Option option = new Option();
			option.setContent(content);
			
			subject.getOptions().add(option);
		}
		
		try {
			//2 创建业务逻辑对象，调用业务方法处理数据
			SubjectService subjectService=new SubjectServiceImpl();
			if(sid==null || sid.trim().length() == 0){
				subjectService.add(subject,(User)request.getSession().getAttribute(User.SESSION_NAME));
			}else{
				subject.setId(Long.parseLong(sid));
				subject.setStartTime(DateUtil.toLong(startTime));
				subject.setEndTime(DateUtil.toLong(endTime));
				subjectService.modify(subject,(User)request.getSession().getAttribute(User.SESSION_NAME));
			}
			
			//3 衔接JSP：
			response.sendRedirect(request.getContextPath()+"/list.do");
			
		}catch(RuleException re){
			request.setAttribute("message", re.getMessage());
			request.getRequestDispatcher("/WEB-INF/pages/add.jsp")
			    .forward(request, response);			
			
		}catch (Exception e) {	
			//TODO  统一异常处理
			e.printStackTrace();
		}
	}


	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
